package com.yungu.swift.admin.route.supervision;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.model.PageVo;
import com.yungu.swift.base.model.admin.AdminPageParam;
import com.yungu.swift.system.supervision.model.dto.ScheduleLogDto;
import com.yungu.swift.system.supervision.service.ScheduleLogService;
import com.yungu.swift.utils.HttpUtils;
import com.yungu.swift.utils.YamlUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/admin/v1/supervision")
@Api(value = "【监管平台】", tags = "监管数据运维")
public class SupervisionAdmin {

    @Reference
    private ScheduleLogService scheduleLogService;

    @RequestMapping(value = "/queryPage", method = RequestMethod.POST)
    @ApiOperation(value = "监管数据分页查询", httpMethod = "POST")
    public ResponseData<PageVo<ScheduleLogDto>> queryPage(@RequestBody AdminPageParam adminPageParam) {
        return scheduleLogService.queryPage(adminPageParam);
    }

    @RequestMapping(value = "/retry", method = RequestMethod.POST)
    @ApiOperation(value = "错误接口重试", httpMethod = "POST")
    public ResponseData<Boolean> retry(@RequestParam String interfaceUrl, @RequestParam String paramsStr, @RequestParam String ipcType) {
        Map<String, Object> map = YamlUtils.load("application.yml");
        String supervisionScheduleServer = String.valueOf(map.get("supervision.schedule.server"));
        Map<String, Object> paramsMap = new HashMap<>(8);
        paramsMap.put("interfaceUrl", interfaceUrl);
        paramsMap.put("paramsStr", paramsStr);
        paramsMap.put("ipcType", ipcType);
        Map<String, Object> responseMap = HttpUtils.post(supervisionScheduleServer + "/api/regulator/postJgBjResendApi", paramsMap);
        String result = (String) responseMap.get("result");
        ResponseData responseData = null;
        try {
            responseData = new ObjectMapper().readValue(result, ResponseData.class);
        } catch (IOException e) {
            log.error("SupervisionAdmin retry readValue error. result:{}", result, e);
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "重发失败：响应数据解析异常");
        }
        Integer status = (Integer) responseMap.get("status");
        if (HttpStatus.SC_OK == status && responseData != null) {
            if (responseData.isSuccess()) {
                return ResponseData.buildSuccessResponse("重发成功", Boolean.TRUE);
            }
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "重发失败");
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "重发失败：请求重发接口异常");
    }
}
